<template>
  <j-modal
    switchFullscreen
    :title="title"
    :width="1200"
    :visible="visible"
    :maskClosable="false"
    :confirmLoading="confirmLoading"
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button type="primary" @click="handleOk" v-if="!disableSubmit">确认</a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :md="8" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="配置名称"
            >
              <a-input :disabled="disableSubmit" placeholder="请输入"
                       v-decorator="['configName',validatorRules.terminalName ]"/>
            </a-form-item>
          </a-col>
<!--          <a-col :md="8" :sm="24">-->
<!--            <a-form-item-->
<!--              :labelCol="labelCol"-->
<!--              :wrapperCol="wrapperCol"-->
<!--              label="配置类型"-->
<!--            >-->
<!--              <a-select-->
<!--                v-decorator.trim="['cfType',validatorRules.terminalName]"-->
<!--                :disabled="disableSubmit"-->
<!--                placeholder="请选择"-->
<!--              >-->
<!--                <a-select-option :value="1">-->
<!--                  字段-->
<!--                </a-select-option>-->
<!--                <a-select-option :value="2">-->
<!--                  属性-->
<!--                </a-select-option>-->
<!--              </a-select>-->
<!--            </a-form-item>-->
<!--          </a-col>-->
          <a-col :md="8" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="配置Vo映射"
            >
              <a-input :disabled="disableSubmit" placeholder="请输入"
                       v-decorator="['mappingFieldName']"/>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="显示类型"
            >
              <a-select
                v-decorator.trim="[ 'showType',validatorRules.terminalName]"
                :disabled="disableSubmit"
                placeholder="请选择"
              >
                <a-select-option :value="1">
                  表单
                </a-select-option>
                <a-select-option :value="2">
                  列表
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :md="8" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="映射配置编码"
            >
              <a-input :disabled="disableSubmit" placeholder="请输入" v-decorator="['configRelCode', ]"/>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    <div style="display: flex;padding-left: 5.5%;border-top: 1px dashed #fefefe;padding-top:10px">
    </div>
    <a-tabs default-active-key="1" @change="callback">
      <a-tab-pane key="1" tab="明细信息">
        <a-button type="primary" @click="insertEvent" style="margin-bottom: 8px" :disabled="disableSubmit">新增</a-button>
        <vxe-table
          border
          resizable
          show-overflow
          size="mini"
          ref="xTable"
          height="500"
          :loading="loading"
          :data="tableData"
          :edit-rules="validRules"
          :edit-config="{trigger: 'click', mode: 'row', enabled:!disableSubmit, showUpdateStatus: true, showInsertStatus: true}">
          <vxe-column type="checkbox" width="40"></vxe-column>
          <vxe-column field="fieldName" title="字段名称" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input v-model="row.fieldName" type="text"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="fieldValue" title="表字段" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input v-model="row.fieldValue" type="text"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="fieldType" title="表字段类型" :edit-render="{}">
            <template #default="{ row }">
              <span>{{ formatTableValue(fieldTypeList, row.fieldType) }}</span>
            </template>
            <template #edit="{ row }">
              <vxe-select v-model="row.fieldType" type="text" :options="fieldTypeList" transfer></vxe-select>
            </template>
          </vxe-column>
          <vxe-column field="fieldLen" title="表字段长度" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input v-model="row.fieldLen" type="integer"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="fieldObj" title="实体类字段" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input v-model="row.fieldObj" type="text"></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="isShow" title="是否显示" :edit-render="{}">
            <template #default="{ row }">
              <span>{{ formatTableValue(showList, row.isShow) }}</span>
            </template>
            <template #edit="{ row }">
              <vxe-select v-model="row.isShow" type="text" :options="showList" transfer></vxe-select>
            </template>
          </vxe-column>
          <vxe-column field="controlType" title="控件类型" :edit-render="{}">
            <template #default="{ row }">
              <span>{{ formatTableValue(controlTypeList, row.controlType) }}</span>
            </template>
            <template #edit="{ row }">
              <vxe-select v-model="row.controlType" type="text" :options="controlTypeList" transfer></vxe-select>
            </template>
          </vxe-column>

          <vxe-column field="fieldSort" title="顺序" :edit-render="{}">
            <template #edit="{ row }">
              <vxe-input v-model="row.fieldSort" type="integer"></vxe-input>
            </template>
          </vxe-column>

          <vxe-column title="操作" width="240">
            <template #default="{ row }">
              <vxe-button status="warning" content="删除" @click="removeRowEvent(row)"
                          :disabled="disableSubmit"></vxe-button>
            </template>
          </vxe-column>
        </vxe-table>
      </a-tab-pane>
    </a-tabs>
    </a-spin>
  </j-modal>
</template>

<script>
import { getAction, httpAction, postAction } from '@/api/manage'
import { pick } from 'lodash'
import moment from 'moment'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import CnAreaLinkage from '@comp/cn-form/CnAreaLinkage'
import { isMobile, isPermit } from '@/utils/validate'
import UploadImage from '@/components/upload-image/UploadImage'
import JImageUpload from '@/components/cn-form/JImageUpload'
import Area from '@/components/utils/Area'
import JUpload from '@/components/cn-form/JUpload'
import { initDictOptions } from '@comp/dict/CnDictSelectUtil'

const generateUUID = function (withSeparator = true) {
  let d = new Date().getTime()
  d = (d + '').substring(5, (d + '').length)
  return d * 1
}
export default {
  name: 'terminal-modal',
  components: { JTreeSelect, CnAreaLinkage, UploadImage, JImageUpload, JUpload },
  data() {
    return {
      validRules: {
        fieldName: [
          { required: true, message: '字段名称必须填写' }
        ],
        fieldValue: [
          { required: true, message: '表字段必须填写' }
        ],
        fieldType: [
          { required: true, message: '表字段类型必须填写' }
        ],
        fieldLen: [
          { required: true, message: '表字段长度必须填写' }
        ],
        fieldObj: [
          { required: true, message: '实体类字段必须填写' }
        ],
        isShow: [
          { required: true, message: '是否显示必须选择' }
        ],
        fieldSort: [
          { required: true, message: '顺序必须填写' }
        ],

      },
      showList: [
        { label: '是', value: '1' },
        { label: '否', value: '0' }
      ],
      controlTypeList: [
        { label: '文本', value: '1' },
        { label: '输入框', value: '2' },
        { label: '选择框', value: '3' }
      ],
      fieldTypeList:[
        { label: 'varchar', value: 'varchar'},
        { label: 'int', value: 'int'},
        { label: 'numeric', value: 'numeric'},
        { label: 'datetime', value: 'datetime'},
        { label: 'date', value: 'date'},
        { label: 'float', value: 'float'},
        { label: 'longtext', value: 'longtext'},
      ],
      dataSurces: [],
      title: '操作',
      visible: false,
      model: {},
      tableData: [],
      labelCol: {
        xs: { span: 24 },
        sm: { span: 9 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 14 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      selectedRowKeys: [],
      selectionRows: [],
      validatorRules: {
        terminalName: {
          rules: [
            { required: true, message: ' ' }
          ]
        },
      },
      addOrUpdateUrl: window._CONFIG['domianActivitiURL'] + '/bsconfig/actBusinessConfig/saveOrUpdate'
    }
  },
  created() {
    this.initAreaData()
    this.initDictConfig()
  },
  methods: {
    moment,
    add() {
      this.edit({})
    },
    initDictConfig() {
      //初始化字典 - 流程分类
      initDictOptions('control_type_list').then((res) => {
        if (res.success) {
          this.controlTypeList = res.result.map(item=>Object.assign({},{label:item.dictDataDesc,value: item.dictDataCode}))
        }
      });
    },
    edit(record) {
      this.form.resetFields()
      this.model = Object.assign({}, record)
      this.visible = true
      this.$nextTick(() => {
        if (record.id) {
          this.tableData = record.detailVos || []
          debugger
        }
        this.form.setFieldsValue(pick(this.model, Object.keys(this.model)))
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.tableData = []
    },
    async insertEvent() {
      const $table = this.$refs.xTable
      const newRecord = {}
      const { row: newRow } = await $table.insert(newRecord)
      newRow.isShow = '1'
      newRow.controlType = 'input'
      newRow.fieldType = 'varchar'
      newRow.fieldLen = 32
      await $table.setActiveRow(newRow)
    },
    async removeSelectEvent() {
      const $table = this.$refs.xTable
      await $table.removeCheckboxRow()
    },
    formatTableValue(list = [], value) {
      console.log(list, value)
      if (list.length) {
        let item = list.find(val => val.value == value)
        console.log(item)
        if (item) {
          return item.label
        } else {
          return ''
        }
      } else {
        return ''
      }
    },

    async handleOk() {
      const that = this
      // 触发表单验证
      const $table = this.$refs.xTable
      const { tableData } = $table.getTableData()
      const errMap = await $table.validate().catch(errMap => errMap)
      if (errMap) {
        return
      }
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true
          let formData = Object.assign(this.model, values, {
            detailVos: tableData,
          })
          httpAction(this.addOrUpdateUrl, formData, 'post').then((res) => {
            if (res.success) {
              this.close()
              that.$emit('ok')
              that.$message.success(res.message)
            } else {
              that.$message.warning(res.message)
            }
          }).finally(() => {
            that.confirmLoading = false
          })
        }
      })
    },
    async removeRowEvent(row) {
      const $table = this.$refs.xTable
      await $table.remove(row)
    },
    handleCancel() {
      this.close()
    },
    initAreaData() {
      if (!this.areaData) {
        this.areaData = new Area()
      }
    },

    // 新增行
    handleAddRow(name) {
      console.log(this[name])
      this[name].push({ id: generateUUID(false) })
    }

  }
}
</script>

<style scoped>
.gonghuoxinxi {
  width: 100%;
  border-bottom: 1px dashed black;
  margin: 10px 0;
  padding: 15px 5px;
  display: flex;
  flex-direction: column;
}
</style>
